package cn.wp.common.core.web.interceptor;


import cn.hutool.core.date.DateUtil;
import cn.wp.common.core.Wp;
import cn.wp.common.core.WpVar;
import cn.wp.common.core.authentication.AuthenticationContext;
import cn.wp.common.core.authentication.AuthenticationInfo;
import cn.wp.common.core.id.Id;
import cn.wp.common.core.module.log.AccessLogDto;
import cn.wp.common.core.util.IpUtil;
import cn.wp.common.core.web.WpWebContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 日志拦截器
 * 配置WpGlobalExceptionAdvice使用
 * Created by chenyb on 2019-09-29
 */
public class LogInterceptor extends WpAbstractInterceptor {

    private static final String START_TIME = "logStartTime";

    public LogInterceptor(String[] pathPatterns, String[] ignores) {
        super(pathPatterns, ignores);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        boolean logEnable = Wp.self().getWpProperties().isLogEnable();
        if(logEnable){
            AuthenticationInfo authenticationInfo = AuthenticationContext.self().currentUser();
            if(authenticationInfo == null){
                authenticationInfo = new AuthenticationInfo();
                authenticationInfo.setId(WpVar.GHOST);
                authenticationInfo.setUserName(WpVar.GHOST);
                authenticationInfo.setAccount(WpVar.GHOST);
            }

            AccessLogDto accessLogDto = new AccessLogDto();
            if(authenticationInfo != null) {
                accessLogDto.setId(Id.gen());
                accessLogDto.setUserId(authenticationInfo.getId());
                accessLogDto.setUserAccount(authenticationInfo.getAccount());
                accessLogDto.setUserName(authenticationInfo.getUserName());
                accessLogDto.setCreateDatetime(DateUtil.date());
                accessLogDto.setIpAddress(IpUtil.getIpAddress(WpWebContext.getRequest()));
                accessLogDto.setResourceUrl(WpWebContext.getRequest().getRequestURI());
                accessLogDto.setStatus(0);
                request.setAttribute(WpVar.LOG_DTO_KEY ,accessLogDto);
                request.setAttribute(START_TIME,System.currentTimeMillis());
            }
        }
        return  true;
    }

    @Override
    public void finalHandle(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        AccessLogDto accessLogDto = (AccessLogDto) request.getAttribute(WpVar.LOG_DTO_KEY);
        if(accessLogDto != null){
            // ControllerAdvice定义后，此处ex为空，获取不到
            if(ex != null){
                StringWriter stackTrace = new StringWriter();
                ex.printStackTrace(new PrintWriter(stackTrace));
                stackTrace.flush();
                accessLogDto.setStatus(1);
                accessLogDto.setTrace(stackTrace.toString());
            }

            long start = (Long)request.getAttribute(START_TIME);
            // 单位：ms
            accessLogDto.setCost(System.currentTimeMillis() - start);
            //accessLogService.saveLog(accessLogDto);
            request.setAttribute(WpVar.LOG_DTO_KEY ,accessLogDto);
        }
    }
}